using System.Collections;
using UnityEngine;

public class TimeManager : MonoBehaviour
{
    // 单例模式
    public static TimeManager Instance { get; private set; }

    [Header("默认游戏时间缩放")]
    [Range(0f, 2f)] public float defaultTimeScale = 1;

    [Header("时间缩放程度")]
    [SerializeField, Range(0f, 2f)] private float bulletTimeScale;
    [Header("多久恢复到默认游戏时间")]
    [SerializeField] private float timeRecoveryDuration;

    private void Awake()
    {
        // 确保只有一个实例存在，如果存在多个则销毁新的实例
        if (Instance == null)
        {
            Instance = this;
        }
        else if (Instance != this)
        {
            Destroy(gameObject);
        }

        DontDestroyOnLoad(gameObject); // 切换场景时不销毁游戏对象，确保对象持久存在
        
        Time.timeScale = defaultTimeScale;
    }

    // 进入减速模式
    public void BulletTime()
    {
        Time.timeScale = bulletTimeScale;
        StartCoroutine(nameof(TimeRecoveryCoroutine));
    }

    // 恢复到默认时间缩放的协程
    IEnumerator TimeRecoveryCoroutine()
    {
        float ratio = 0f;
        while (ratio < 1f)
        {
            ratio += Time.unscaledDeltaTime / timeRecoveryDuration;
            // 插值时间缩放从减速时间缩放到默认时间缩放
            Time.timeScale = Mathf.Lerp(bulletTimeScale, defaultTimeScale, ratio);

            yield return null; // 等待下一帧继续执行
        }
    }
}
